<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '院系添加' : '院系编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="30%"
      center
    >
      <el-form
        ref="departmentForm"
        :model="departmentForm"
        label-width="100px"
        fullscreenLoading
        class="formStyle"
        :rules="departmentFormRules"
      >
        <el-form-item label="院系名" :prop="isAdd ? 'name' : 'editName'">
          <el-input
            v-model="departmentForm.name"
            placeholder="请输入院系名称"
            class="inputWdith"
          ></el-input>
        </el-form-item>
        <el-form-item label="院系热线">
          <el-input
            v-model="departmentForm.phone"
            placeholder="请输入院系电话"
            class="inputWdith"
          ></el-input>
        </el-form-item>
        <el-form-item label="院系描述">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="departmentForm.description"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('departmentForm')"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确认</el-button
          >
          <el-button @click="resetForm('departmentForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入院系名"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="departmentName"
          >
          </el-input>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="departmentTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="departments"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
            @row-click="rowClick"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="院系描述：">
                    <span>{{ props.row.description || '无' }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="院系编号"> </el-table-column>
            <el-table-column prop="name" label="院系名"> </el-table-column>
            <el-table-column prop="phone" label="院系热线"> </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'DepartmentMng',
  data() {
    let validateNameIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('请输入院系名称')]);
      }
      if (this.isAdd) {
        // 检查是否重名
        let result = await this.$store.dispatch(
          'AcademyMng/checkIsRepeatForDepartmentName',
          value
        );
        return result.data.flag
          ? callback()
          : callback([new Error(result.message)]);
      }
    };
    return {
      isAdd: false, // 是否为点击新增按钮打开的模态窗口
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数
      condition: {},
      departmentName: '',
      departments: [],
      loading: false, // 遮罩层
      centerDialogVisible: false, // 对话框开关
      departmentForm: {}, // 院系表单对象
      fullscreenLoading: false, // 遮罩层
      departmentFormRules: {
        name: [
          {
            required: true,
            validator: validateNameIsRepeat,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  watch: {
    departmentList() {
      this.$set(this, 'departments', this.departmentList);
      this.loading = false;
    },
    departmentIPage() {
      this.currentPage = this.departmentIPage.currentPage;
      this.pageSize = this.departmentIPage.pageSize;
      this.total = this.departmentIPage.total;
    },
  },
  computed: {
    ...mapGetters('AcademyMng', ['departmentList', 'departmentIPage']),
  },
  mounted() {
    this.getDepartmentList();
  },
  methods: {
    // 刷新院系列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getDepartmentList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 删除院系
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('AcademyMng/batchDelDepartment', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getDepartmentList();
        })
        .catch(() => {
          this.$message({
            message: result ? result.messag : '取消删除',
            type: 'info',
            duration: 2 * 1000,
          });
        });
    },
    // 编辑院系
    handEdit(row) {
      let temp = {
        ...row,
      };
      this.departmentForm = temp;
      this.centerDialogVisible = true;
    },

    // 新增院系
    handleAdd() {
      this.departmentForm = {};
      this.isAdd = true;
      this.centerDialogVisible = true;
    },

    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {};
      if (this.departmentName) {
        this.condition.name = this.departmentName;
      }
      await this.getDepartmentList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getDepartmentList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartmentList();
    },

    // 点击行,跳转至专业页面,显示对应的专业
    rowClick(row) {
      // 路由至专业组件
      this.$router.push({
        name: 'majorList',
        params: {
          departmentId: row.id,
        },
      });
    },

    // 查询院系列表
    getDepartmentList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('AcademyMng/getDepartmentList', params);
    },

    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            let result = {};
            // 将院系专业拆分出来
            if (this.isAdd) {
              let paramsArray = [];
              // 发送请求
              let params = {
                ...this.departmentForm,
              };
              paramsArray.push(params);

              result = await this.$store.dispatch(
                'AcademyMng/batchAddDepartmentList',
                paramsArray
              );
            } else {
              result = await this.$store.dispatch(
                'AcademyMng/editDepartment',
                this.departmentForm
              );
            }
            // 执行成功返回结果，
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
            // 更新院系列表
            this.getDepartmentList();
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false; // 关闭遮罩层
            this.isAdd = false; // 重置表单状态
            this.centerDialogVisible = false; // 关闭模态窗口
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
/* 分页居中 */
.block {
  text-align: center;
}
</style>
